<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
class GuestMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->header('x-access-token');
        $key = $request->header('key');
        $origin = $request->header('Origin');
        if (!$origin ){
            return response('无权访问!',401);
        }
        $iv = '8Z2wMy7amABbqsRC'; // 一个随机的 16 字节初始向量
        $method = 'AES-256-CBC'; // 使用 AES-256-CBC 加密算法
        $decryptedData = openssl_decrypt(base64_decode($token), $method, $key, OPENSSL_RAW_DATA, $iv); // 执行解密操作
        if ($decryptedData === false) {
            return response()->json(['error' => '解密失败'], 403);
        }

        $timestamp = trim(str_replace($key.'/','',$decryptedData),'"');

        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        if ($msectime > (int)$timestamp + 60000){
            return response()->json(['error'=>'访问出错,无权访问!'],401);
        }
        // var_dump($decryptedData);
        return $next($request);
    }
}
